package com.lemon.smartsafety.ui.fragment.safe.data;

import android.content.Context;
import android.graphics.drawable.BitmapDrawable;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.PopupWindow;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.ldzs.recyclerlibrary.Mode;
import com.ldzs.recyclerlibrary.PullToRefreshRecyclerView;
import com.lemon.smartsafety.R;
import com.lemon.smartsafety.app.AppService;
import com.lemon.smartsafety.app.BundleKey;
import com.lemon.smartsafety.app.EventTag;
import com.lemon.smartsafety.app.RefreshType;
import com.lemon.smartsafety.entity.common.SelectDataI;
import com.lemon.smartsafety.entity.event.datacoll.BuildListItemEvent;
import com.lemon.smartsafety.entity.event.datacoll.BuildingRefreshEvent;
import com.lemon.smartsafety.entity.event.datacoll.KeyWordEvent;
import com.lemon.smartsafety.entity.event.datacoll.PopupEvent;
import com.lemon.smartsafety.entity.event.http.HttpCallbackEvent;
import com.lemon.smartsafety.entity.event.safe_manager.BuildingListFragmentRefresh;
import com.lemon.smartsafety.entity.safe.company.CompanyBuildingVo;
import com.lemon.smartsafety.entity.safe.company.CompanyInfo;
import com.lemon.smartsafety.http.service.SafeDataServices;
import com.lemon.smartsafety.listener.RecyclerTClickListener;
import com.lemon.smartsafety.ui.adapter.common.SelectAdapter;
import com.lemon.smartsafety.ui.adapter.safe.data.BuildingListAdapter;
import com.lemon.smartsafetynew.ui.fragment.base.BasePullToRefreshFragment;
import com.lemon.smartsafety.utils.SystemUtil;
import com.lemon.smartsafety.utils.common.StringUtils;
import com.lemon.smartsafety.view.list.MultiStateView;
import com.zhy.http.okhttp.OkHttpUtils;

import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;

import kale.adapter.LemonRcvAdapter;

/**
 * 项目名称：workspace
 * 类描述：
 * 创建人：Fargo
 * 创建时间：2016/9/2 16:49
 * 修改人：Fargo
 * 修改时间：2016/9/2 16:49
 * 修改备注：
 */
public class BuildingListNewFragment extends BasePullToRefreshFragment<CompanyBuildingVo, List<CompanyBuildingVo>> implements RecyclerTClickListener<CompanyBuildingVo> {
    //private LoggerHelper loggerHelper = new LoggerHelper(BuildingListNewFragment.class);

    private String mSearchText = "";
    private CompanyInfo mCompanyInfo;

    /**
     * 是否是安全巡查界面过来的
     */
    private boolean isSafeInspection = false;


    /**
     * 条件筛选
     */
    private View mPopParentView;
    private PopupWindow mPopupWindow;
    private EditText mPopEtKeyWord;
    private MultiStateView mFilterMultiStateView;
    private PullToRefreshRecyclerView mGroupPullToRefreshRecyclerView;
    private Button btnFilterSure, btnFilterClear;
    private List<SelectDataI> mGroupItems = new ArrayList<>();
    private View           mOtherView;
    private LayoutInflater mInflater;
    private SelectAdapter mGroupAdapter;
    private String mGroupSelectValue = "";

    private Context mContext;


    public static BuildingListNewFragment newInstance() {
        return new BuildingListNewFragment();
    }

    @Override
    protected void getBaseArguments() {
        super.getBaseArguments();
        if (getArguments() != null) {
            mSearchText = getArguments().getString(BundleKey.KEY_WORD);
            mCompanyInfo = (CompanyInfo) getArguments().getSerializable(BundleKey.COMPANY_INFO);
            isSafeInspection = getArguments().getBoolean(BundleKey.IS_SAFE_INSPECTION, false);
        }
    }

    @Override
    protected void initViews() {
        super.initViews();
        mContext = getActivity();
        mInflater = LayoutInflater.from(mContext);
        mPullToRefreshRecyclerView.addOnScrollListener(onScrollListener);
    }

    private RecyclerView.OnScrollListener onScrollListener = new RecyclerView.OnScrollListener() {
        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);
            /* 有问题先取消了
            try {
                LinearLayoutManager manager       = (LinearLayoutManager) recyclerView.getLayoutManager();
                int                 first         = manager.findFirstVisibleItemPosition();
                int                 last          = manager.findLastVisibleItemPosition();
                int                 headViewCount = mPullToRefreshRecyclerView.getHeaderViewCount();
                loggerHelper.w("first = " + first);
                loggerHelper.w("headViewCount = " + headViewCount);

                for (int i = first; i <= last; i++) {
                    View view = manager.findViewByPosition(i);
                    if (view == null || i == 0) {
                        return;
                    }
                    ImageView ivStatusLight = (ImageView) view.findViewById(R.id.iv_status_light);
                    ((BuildingListAdapter) mAdapter).setStatusLight(i - headViewCount, ivStatusLight);
                }
            } catch (Exception e) {
                if (BuildConfig.DEBUG) {
                    e.printStackTrace();
                }
            }
            */
        }
    };


    @Override
    public boolean goRefreshOnCreate() {
        return true;
    }

    @Override
    public LemonRcvAdapter<CompanyBuildingVo> getLemonAdapter() {
        return new BuildingListAdapter(mDataList, this, isSafeInspection);
    }

    @Override
    public String getHttpTag() {
        return EventTag.TAG_SAFE_DATA_COLLECTION_BUILDING_LIST;
    }

    @Override
    public void onLoadMore() {
        SafeDataServices.init()
                .getAllBuildingList(RefreshType.LOAD_MORE, pageSize, currentPage, mCompanyInfo.getCompany_code(), mGroupSelectValue, mSearchText);
    }

    @Override
    public void onPullRefresh() {
        SafeDataServices.init()
                .getAllBuildingList(RefreshType.REFRESH, pageSize, currentPage, mCompanyInfo.getCompany_code(), mGroupSelectValue, mSearchText);
    }


    /**
     * 刷新事件
     *
     * @param event
     */
    @Subscribe
    public void onEventMainThread(BuildingRefreshEvent event) {
        if (EventTag.TAG_SAFE_DATA_COLLECTION_BUILDING_REFRESH.equals(event.getTag())) {
            mPullToRefreshRecyclerView.beginRefreshing();
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        OkHttpUtils.getInstance().cancelTag(EventTag.TAG_SAFE_DATA_COLLECTION_BUILDING_LIST);
        if (mPullToRefreshRecyclerView != null && onScrollListener != null) {
            mPullToRefreshRecyclerView.removeOnScrollListener(onScrollListener);
        }
    }

    @Override
    public void onItemClick(CompanyBuildingVo data, int position) {//把事件交给宿主处理
        BuildListItemEvent event = new BuildListItemEvent();
        event.setTag(BuildingListFragment.class.getName());
        event.setData(data);
        AppService.getBus().post(event);
    }


    /****************************************************************************************************************
     * 筛选数据用的
     ****************************************************************************************************************/
    @Subscribe
    public void onEventMainThread(PopupEvent event) {
        getPopWindow().showAsDropDown(mTopLine, 0, 0);
        if (StringUtils.nullValue(event.getKeyword()).length() != 0) {
            mPopEtKeyWord.setText(event.getKeyword());
            mSearchText = event.getKeyword();
        }
        mGroupItems.clear();
        mGroupItems.addAll(event.getData());
        if (mGroupItems.isEmpty()) {
            mFilterMultiStateView.setEmptyTip("还没有分组数据");
        }else{
            mFilterMultiStateView.setViewState(MultiStateView.VIEW_STATE_CONTENT);
            mGroupAdapter.notifyDataSetChanged();
        }
    }


    private PopupWindow getPopWindow() {
        initPopView();
        if (mPopupWindow == null) {
            mPopupWindow = new PopupWindow(mContext);
            mPopupWindow.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
            mPopupWindow.setHeight(ViewGroup.LayoutParams.MATCH_PARENT);
            // 实例化一个ColorDrawable颜色为半透明
            mPopupWindow.setBackgroundDrawable(new BitmapDrawable());
            mPopupWindow.setFocusable(true);
            mPopupWindow.setOutsideTouchable(true);
            mPopupWindow.setContentView(mPopParentView);
        }
        return mPopupWindow;
    }

    private void initPopView() {
        if (mPopParentView == null || mGroupPullToRefreshRecyclerView == null || mFilterMultiStateView == null) {//加载pop的内部视图
            mPopParentView = mInflater.inflate(R.layout.pop_build_filter, null);
            mGroupPullToRefreshRecyclerView = (PullToRefreshRecyclerView) mPopParentView.findViewById(R.id.pullToRefreshRecyclerView);
            LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
            mGroupPullToRefreshRecyclerView.setRefreshMode(Mode.DISABLED);
            mGroupPullToRefreshRecyclerView.setOnPullUpToRefreshListener(new PullToRefreshRecyclerView.OnPullUpToRefreshListener() {
                @Override
                public void onRefresh() {

                }
            });

            mGroupAdapter = new SelectAdapter(mGroupItems, new RecyclerTClickListener<SelectDataI>() {
                @Override
                public void onItemClick(SelectDataI data, int position) {
                    mGroupSelectValue = data.getValue();
                    mGroupAdapter.setSelectedByPositionSingle(position);
                }
            }, mGroupSelectValue);


            mGroupPullToRefreshRecyclerView.setLayoutManager(layoutManager);
            mGroupPullToRefreshRecyclerView.setAdapter(mGroupAdapter);  // requires *wrapped* adapter


            mPopEtKeyWord = (EditText) mPopParentView.findViewById(R.id.edit_key_word);

            btnFilterSure = (Button) mPopParentView.findViewById(R.id.btn_sure);
            btnFilterSure.setOnClickListener(onClickListener);

            btnFilterClear = (Button) mPopParentView.findViewById(R.id.btn_clear);
            btnFilterClear.setOnClickListener(onClickListener);

            mFilterMultiStateView = (MultiStateView) mPopParentView.findViewById(R.id.multiStateView);
            mFilterMultiStateView.setViewState(MultiStateView.VIEW_STATE_LOADING);

            mOtherView = mPopParentView.findViewById(R.id.vOther);
            mOtherView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mPopupWindow.dismiss();
                }
            });

        }
    }

    private View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (v.getId() == R.id.btn_sure) {
                mPopupWindow.dismiss();
                mSearchText = mPopEtKeyWord.getText().toString().trim();
                KeyWordEvent event = new KeyWordEvent();
                event.setData(mGroupItems);
                event.setKeyword(mSearchText);
                AppService.getBus().post(event);
                doPullRefresh();
                SystemUtil.HideKeyboard(getActivity());
            } else if (v.getId() == R.id.btn_clear) {

                getConfirmDialog("是否清空？", new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        if (which == DialogAction.POSITIVE) {
                            mPopEtKeyWord.setText("");
                            mGroupSelectValue = "";
                            mPopupWindow.dismiss();
                            mSearchText = mPopEtKeyWord.getText().toString().trim();
                            KeyWordEvent event = new KeyWordEvent();
                            event.setKeyword(mSearchText);
                            AppService.getBus().post(event);
                            doPullRefresh();
                        }
                    }
                }).show();
            }
        }
    };


    @Override
    public void onEventMainThread(HttpCallbackEvent event) {

        super.onEventMainThread(event);
    }


    /**
     * 执行下拉刷新
     * @param event
     */
    @Subscribe
    public void onEventMainThread(BuildingListFragmentRefresh event) {

        doPullRefresh();
    }




}
